package com.cqhz.quwan.ui.main.match.fragment;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.TextView;

import com.whamu2.treeview.adpater.TreeRecyclerAdapter;
import com.whamu2.treeview.adpater.TreeRecyclerType;
import com.whamu2.treeview.factory.ItemHelperFactory;
import com.whamu2.treeview.item.TreeItem;
import com.cqhz.quwan.ActivityInject;
import com.cqhz.quwan.R;
import com.cqhz.quwan.model.AnalysisRecord;
import com.cqhz.quwan.model.AnalysisVote;
import com.cqhz.quwan.model.LoginBean;
import com.cqhz.quwan.mvp.match.AnalysisContract;
import com.cqhz.quwan.mvp.match.AnalysisPresenter;
import com.cqhz.quwan.ui.base.AbsFragment;
import com.cqhz.quwan.ui.main.match.adapter.tree.AnalysisMainTitleTree;
import com.cqhz.quwan.ui.main.match.common.Key;
import com.cqhz.quwan.ui.main.match.entity.RecordData;
import com.cqhz.quwan.ui.widget.CallSupportViewGroup;
import com.cqhz.quwan.ui.widget.FullyLinearLayoutManager;
import com.cqhz.quwan.util.LoginObserver;
import com.cqhz.quwan.util.LoginSubscribe;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.inject.Inject;

import me.militch.quickcore.core.HasDaggerInject;


/**
 * 分析
 *
 * @author whamu2
 * @date 2018/7/17
 */
public class AnalysisFragment extends AbsFragment implements CallSupportViewGroup.OnCheckedChangeListener,
        AnalysisContract.View, HasDaggerInject<ActivityInject>, LoginSubscribe {
    private static final String TAG = AnalysisFragment.class.getSimpleName();
    private static final String KEY_INTEGRAL = "integral";

    private TextView mVoteTextView;
    private RecyclerView mRecyclerView;
    private CallSupportViewGroup mHostViewGroup;
    private CallSupportViewGroup mLevelViewGroup;
    private CallSupportViewGroup mGuestViewGroup;
    private View mEmptyView;

    private TreeRecyclerAdapter mTreeRecyclerAdapter
            = new TreeRecyclerAdapter(TreeRecyclerType.SHOW_ALL);

    private String code;

    @Inject
    AnalysisPresenter mPresenter;

    /**
     * 是否投票 投了什么类型的票
     */
    private int mVoteType = Key.Analysis.VOTE_DEFAULT;

    @Override
    public void inject(ActivityInject inject) {
        inject.inject(this);
    }

    public static AnalysisFragment newInstance(String code) {
        Bundle args = new Bundle();
        args.putString(KEY_INTEGRAL, code);
        AnalysisFragment fragment = new AnalysisFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int layout() {
        return R.layout.fragment_match_analysis;
    }

    @Override
    public void initView() {

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            code = getArguments().getString(KEY_INTEGRAL);
        }
    }

    @Override
    public void onViewCreated(@NonNull View view,
                              @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mPresenter.attachView(this);
        LoginObserver.register(this);
        mRecyclerView = view.findViewById(R.id.rv);
        mVoteTextView = view.findViewById(R.id.tv_vote);
        mHostViewGroup = view.findViewById(R.id.call_host);
        mLevelViewGroup = view.findViewById(R.id.call_level);
        mGuestViewGroup = view.findViewById(R.id.call_guest);
        mEmptyView = view.findViewById(R.id.tv_empty);
        mHostViewGroup.setOnCheckedChangeListener(this);
        mLevelViewGroup.setOnCheckedChangeListener(this);
        mGuestViewGroup.setOnCheckedChangeListener(this);

        FullyLinearLayoutManager mLayoutManager = new FullyLinearLayoutManager(getContext());
        mRecyclerView.setLayoutManager(mLayoutManager);
        mLayoutManager.setSmoothScrollbarEnabled(true);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        mPresenter.getAnalysisRecord();
    }

    @Override
    public void onCheckedChanged(CallSupportViewGroup group, boolean isChecked) {
        switch (group.getId()) {
            case R.id.call_host:
                if (checkLogin()) {
                    if (mVoteType == -1) {
                        mPresenter.addAnalysisVote(Key.Analysis.VOTE_HOST);
                    }
                } else {
                    mHostViewGroup.setChecked(false);
                }
                break;
            case R.id.call_level:
                if (checkLogin()) {
                    if (mVoteType == -1) {
                        mPresenter.addAnalysisVote(Key.Analysis.VOTE_LEVEL);
                    }
                } else {
                    mLevelViewGroup.setChecked(false);
                }
                break;
            case R.id.call_guest:
                if (checkLogin()) {
                    if (mVoteType == -1) {
                        mPresenter.addAnalysisVote(Key.Analysis.VOTE_GUEST);
                    }
                } else {
                    mGuestViewGroup.setChecked(false);
                }
                break;
        }
    }

    @Override
    public void getVoteResult(AnalysisVote vote) {
        setupVote(vote);
    }

    @Override
    public void voteFail() {
        mHostViewGroup.setChecked(false);
        mLevelViewGroup.setChecked(false);
        mGuestViewGroup.setChecked(false);
        mHostViewGroup.setEnabled(true);
        mLevelViewGroup.setEnabled(true);
        mGuestViewGroup.setEnabled(true);
    }

    @Override
    public void getRecord(List<AnalysisRecord.RecordPOListBean> data) {
        if (data != null && data.size() > 0) {
            List<TreeItem> treeItemList = ItemHelperFactory.createTreeItemList(getOrigin(data), AnalysisMainTitleTree.class, null);
            mRecyclerView.setAdapter(mTreeRecyclerAdapter);
            mTreeRecyclerAdapter.getItemManager().replaceAllItem(treeItemList);

            mEmptyView.setVisibility(View.GONE);
        } else {
            mEmptyView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void getRecordFail() {
        mEmptyView.setVisibility(View.GONE);
    }

    /**
     * 合并战绩
     *
     * @param data {@link AnalysisRecord.RecordPOListBean}
     * @return List<RecordData>
     */
    public static List<RecordData> getOrigin(List<AnalysisRecord.RecordPOListBean> data) {
        List<RecordData> recordData = new ArrayList<>();

        RecordData zkd = new RecordData();
        zkd.setCount(2);
        zkd.setTitle("主客队历史交锋");
        List<AnalysisRecord.RecordPOListBean> zkds = new ArrayList<>();
        zkd.setData(zkds);

        RecordData zd = new RecordData();
        zd.setCount(4);
        zd.setTitle("主队近期战绩");
        List<AnalysisRecord.RecordPOListBean> zds = new ArrayList<>();
        zd.setData(zds);

        RecordData kd = new RecordData();
        kd.setCount(6);
        kd.setTitle("客队近期战绩");
        List<AnalysisRecord.RecordPOListBean> kds = new ArrayList<>();
        kd.setData(kds);

        for (AnalysisRecord.RecordPOListBean bean : data) {
            if (bean.getRecord_type() == Key.Analysis.ZKDLSJF) { // 主客队历史交锋
                zkds.add(bean);
            }
            if (bean.getRecord_type() == Key.Analysis.ZDJQZJ) { // 主队近期战绩
                zds.add(bean);
            }
            if (bean.getRecord_type() == Key.Analysis.ZDWLSS) { // 主队未来战绩
                zds.add(bean);
            }
            if (bean.getRecord_type() == Key.Analysis.KDJQZJ) { // 客队近期战绩
                kds.add(bean);
            }
            if (bean.getRecord_type() == Key.Analysis.KDWLSS) { // 客队未来战绩
                kds.add(bean);
            }
        }

        Collections.sort(zds, (o1, o2) -> o1.getRecord_type() - o2.getRecord_type());
        Collections.sort(kds, (o1, o2) -> o1.getRecord_type() - o2.getRecord_type());
        recordData.add(zkd);
        recordData.add(kd);
        recordData.add(zd);
        Collections.sort(recordData, (o1, o2) -> o1.getCount() - o2.getCount());

        return recordData;
    }

    @Override
    public void getVote(AnalysisVote vote) {
        mVoteTextView.setText(MessageFormat.format("{0}人已投票", "46354"));
        //mHostViewGroup.setProgress((float) (vote.getVoteWin() * 100));
        //mLevelViewGroup.setProgress((float) (vote.getVoteNegative() * 100));
        //mGuestViewGroup.setProgress((float) (vote.getVoteFlat() * 100));
        setupVote(vote);
    }

    private void setupVote(AnalysisVote vote) {
        int win = (int) (vote.getVoteWin() * 100);
        if (win < 0) {
            setAnimator(mHostViewGroup, 0);
        } else if (win > 100) {
            setAnimator(mHostViewGroup, 100);
        } else {
            setAnimator(mHostViewGroup, win);
        }
        int flat = (int) (vote.getVoteFlat() * 100);
        if (flat < 0) {
            setAnimator(mLevelViewGroup, 0);
        } else if (flat > 100) {
            setAnimator(mLevelViewGroup, 100);
        } else {
            setAnimator(mLevelViewGroup, flat);
        }
        int negative = (int) (vote.getVoteNegative() * 100);
        if (negative < 0) {
            setAnimator(mGuestViewGroup, 0);
        } else if (negative > 100) {
            setAnimator(mGuestViewGroup, 100);
        } else {
            setAnimator(mGuestViewGroup, negative);
        }

        mHostViewGroup.setPercent(MessageFormat.format("{0}%", vote.getVoteWin() * 100));
        mLevelViewGroup.setPercent(MessageFormat.format("{0}%", vote.getVoteFlat() * 100));
        mGuestViewGroup.setPercent(MessageFormat.format("{0}%", vote.getVoteNegative() * 100));

        AnalysisVote.VoteBean bean = vote.getVote();
        if (bean != null) {
            mVoteType = bean.getVote_type();
            switch (bean.getVote_type()) {
                case Key.Analysis.VOTE_HOST:
                    mHostViewGroup.setChecked(true);
                    mLevelViewGroup.setChecked(false);
                    mGuestViewGroup.setChecked(false);

                    mHostViewGroup.setEnabled(false);
                    mLevelViewGroup.setEnabled(false);
                    mGuestViewGroup.setEnabled(false);
                    break;
                case Key.Analysis.VOTE_LEVEL:
                    mHostViewGroup.setChecked(false);
                    mLevelViewGroup.setChecked(true);
                    mGuestViewGroup.setChecked(false);

                    mHostViewGroup.setEnabled(false);
                    mLevelViewGroup.setEnabled(false);
                    mGuestViewGroup.setEnabled(false);
                    break;
                case Key.Analysis.VOTE_GUEST:
                    mHostViewGroup.setChecked(false);
                    mLevelViewGroup.setChecked(false);
                    mGuestViewGroup.setChecked(true);

                    mHostViewGroup.setEnabled(false);
                    mLevelViewGroup.setEnabled(false);
                    mGuestViewGroup.setEnabled(false);
                    break;
                default:
                    mHostViewGroup.setChecked(false);
                    mLevelViewGroup.setChecked(false);
                    mGuestViewGroup.setChecked(false);

                    mHostViewGroup.setEnabled(true);
                    mLevelViewGroup.setEnabled(true);
                    mGuestViewGroup.setEnabled(true);
                    break;
            }
        } else {
            mHostViewGroup.setChecked(false);
            mLevelViewGroup.setChecked(false);
            mGuestViewGroup.setChecked(false);

            mHostViewGroup.setEnabled(true);
            mLevelViewGroup.setEnabled(true);
            mGuestViewGroup.setEnabled(true);
        }
    }

    private void setAnimator(@NonNull CallSupportViewGroup group, int progress) {
        ValueAnimator valueAnimator = ObjectAnimator.ofInt(0, progress);
        valueAnimator.setDuration(1000);
        valueAnimator.setStartDelay(800);
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.addUpdateListener(animation -> {
            int value = (Integer) animation.getAnimatedValue();
            group.setProgress(value);
        });
        valueAnimator.start();
    }

    @Override
    public String getUser() {
        return getUserId();
    }

    @Override
    public String getMatchId() {
        return code;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPresenter.detachView();
        LoginObserver.unregister(this);
    }

    @Override
    public void login(LoginBean loginBean) {

    }
}
